const db = require("./db");

function Address(address) {
    this.id = address.id;
    this.userId = address.userId;
    this.address = address.address;
    this.addressDetail = address.addressDetail;
    this.isDelete = address.isDelete;
    this.recipients = address.recipients;
    this.postcode = address.postcode;
}

Address.addAddress = (address, callback) => {
    let selectSql = "insert into address (id,userId,address,addressDetail,isDelete,recipients,postcode)  values (null,?,?,?,1,?,?)";
    db.query(selectSql, [address.userId, address.address, address.addressDetail, address.recipients, address.postcode], (err, result) => {
        console.log("addAddress err=>" + JSON.stringify(err));
        if (err) return callback(err);
        callback(err, result);
    })
}
Address.deleteAddress = (id, callback) => {
    let delSql = "UPDATE address SET isDelete = 0 WHERE id=?";
    db.query(delSql, [id], (err, res) => {
        if (err) return callback(err);
        callback(err, res);
    })
}
Address.updateAddress = (address, callback) => {
    let selectSql = "UPDATE address SET   ";
    let param = new Array();
    if (address.address && param.length == 0) {
        selectSql += " address = ?";
        param[param.length] = address.address;
    }
    if (address.addressDetail && param.length == 0) {
        selectSql += ' addressDetail=? ';
        param[param.length] = address.addressDetail;
    } else if (address.addressDetail && param.length != 0) {
        selectSql += ' ,addressDetail=? ';
        param[param.length] = address.addressDetail;
    }
    if (address.recipients && param.length == 0) {
        selectSql += ' recipients=? ';
        param[param.length] = address.recipients;
    } else if (address.recipients && param.length != 0) {
        selectSql += ' ,recipients=? ';
        param[param.length] = address.recipients;
    }
    if (address.postcode && param.length == 0) {
        selectSql += ' postcode=? ';
        param[param.length] = address.postcode;
    } else if (address.postcode && param.length != 0) {
        selectSql += ' ,postcode=? ';
        param[param.length] = address.postcode;
    }
    selectSql += " WHERE id = ?";
    param[param.length] = address.id;

    console.log(selectSql);
    console.log(param);

    db.query(selectSql, param, (err, res) => {
        if (err) return callback(err);
        callback(err, res);
    })
}
Address.queryAddress = (userId, callback) => {
    let selectSql = "select * from address where userId = ? and isDelete = 1";
    db.query(selectSql, [userId], (err, res) => {
        if (err) return callback(err);
        callback(err, res);
    })
}

module.exports = Address;